<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.List" %>
<%@ page import="javax.jdo.PersistenceManager" %>
<%@ page import="com.google.appengine.api.users.User" %>
<%@ page import="com.google.appengine.api.users.UserService" %>
<%@ page import="com.google.appengine.api.users.UserServiceFactory" %>
<%@ page import="guestbook.Greeting" %>
<%@ page import="guestbook.PMF" %>
<html>  
  <head>
    <link type="text/css" rel="stylesheet" href="/stylesheets/main.css" />
  </head>
  
<body>
<%    UserService userService = UserServiceFactory.getUserService();    
	  User user = userService.getCurrentUser();    
      if (user != null) 
{%>
<p>Hello, <%= user.getNickname() %>! (You can <a href="<%= userService.createLogoutURL(request.getRequestURI()) %>">sign out</a>.)</p>
<%    } else {%>
<p>Hello! <a href="<%= userService.createLoginURL(request.getRequestURI()) %>"> Sign in </a>to include your name with greetings you post.</p>
<%    }%>
<%   
PersistenceManager pm = PMF.get().getPersistenceManager();    
String query = "select from " + Greeting.class.getName() + " order by date desc range 0,5";   
List<Greeting> greetings = (List<Greeting>) pm.newQuery(query).execute();    
if (greetings.isEmpty()) 
{%>

<p>The guestbook has no messages.</p>
<%    
} else {        
	for (Greeting g : greetings) {            %>
        <br>
		<table bgcolor="#ACCE69" border="0" width="80%"
			style="word-break: break-all; margin-top: 3" cellpadding="8"
			cellspacing="1">        		
			<tr bgcolor="#F7FAF4">
				<td>		
		
		<%
			User author = g.getAuthor();
		    String name;
		    if(author == null)
		    	name = "anonymous";
		    else
		    	name = author.getNickname();
		    
		%>
					<div style="margin-top: 0">
						☆ &nbsp;&nbsp;
						<b><u><%=name %></u>
						</b>
					</div>
					
					<%
					  java.text.SimpleDateFormat f = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ssz");
					  String date = f.format(g.getDate());
  					%>
  
		            <div style="margin-top: -20; color: gray" align="right"><%=date %></div>
		 					
					<hr color="#ACCE69">
					<span style="font:normal bold 12pt;color: gray ">
					<%=g.getContent() %>
					</span>
					
					<br>
					<br>
				</td>
			</tr>
		</table>
				
		
	


		<%        }    }    pm.close();%>    
	
	
	
		<form action="/sign" method="post">      
		<div><textarea name="content" rows="3" cols="60"></textarea></div>      
		<div><input type="submit" value="Post Greeting" /></div>    
		</form>  
	
	
		</body>
</html>